package productproperty

import (
	// "net/http"

	"strconv"

	// "time"
	// "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"

	// "github.com/jinzhu/gorm"

	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/res/dicserver/property"
	"oxy_server/until"
)

type (
	designproperty struct {
		ID                bson.ObjectId       `json:"_id" bson:"_id"`
		DesignPlanID      string              `json:"designplanid" bson:"designplanid"`           //设计组ID
		ReferenceBigTag   string              `json:"referencebigtag" bson:"referencebigtag"`     //参考大牌
		SellingPoints     string              `json:"sellingpoints" bson:"sellingpoints"`         //卖点
		StereoType        []string            `json:"stereotype" bson:"stereotype"`               //版型
		ProductName       string              `json:"productname" bson:"productname"`             //商品名称
		DesignCompose     []designCompose     `json:"compose" bson:"compose"`                     //组成
		DesignComposeInfo []property.Property `json:"composeinfo" bson:"composeinfo"`             //组成详细
		PropertyStatus    int                 `json:"propertystatus" bson:"propertystatus"`       //产品属性编辑状态
		DesignManufacture string              `json:"designmanufacture" bson:"designmanufacture"` //设计与工艺
		Cloth             string              `json:"cloth" bson:"cloth"`                         //面料
		Process           string              `json:"process" bson:"process"`                     //工艺
		Match             string              `json:"match" bson:"match"`                         //搭配
		Version           string              `json:"version" bson:"version"`                     //版型

	}
	insertdesignproperty struct {
		DesignPlanID      string              `json:"designplanid" bson:"designplanid"`           //设计组ID
		ReferenceBigTag   string              `json:"referencebigtag" bson:"referencebigtag"`     //参考大牌
		SellingPoints     string              `json:"sellingpoints" bson:"sellingpoints"`         //卖点
		DesignManufacture string              `json:"designmanufacture" bson:"designmanufacture"` //设计与工艺
		StereoType        []string            `json:"stereotype" bson:"stereotype"`               //版型
		ProductName       string              `json:"productname" bson:"productname"`             //商品名称
		DesignCompose     []designCompose     `json:"compose" bson:"compose"`                     //组成
		DesignComposeInfo []property.Property `json:"composeinfo" bson:"composeinfo"`             //组成详细
		PropertyStatus    int                 `json:"propertystatus" bson:"propertystatus"`       //产品属性编辑状态
		Cloth             string              `json:"cloth" bson:"cloth"`                         //面料
		Process           string              `json:"process" bson:"process"`                     //工艺
		Match             string              `json:"match" bson:"match"`                         //搭配
		Version           string              `json:"version" bson:"version"`                     //版型

	}
	designCompose struct {
		Item          string `json:"item" bson:"item"`                   //项目
		Specification string `json:"specification" bson:"specification"` //规格描述
		// Loss          string `json:"loss" bson:"loss"`                   //规格描述
		// Cost          string `json:"cost" bson:"cost"`                   //规格描述
		UnitPrice string `json:"unitprice" bson:"unitprice"` //单价
	}
	QueryPropertyInfo struct {
		ID bson.ObjectId `json:"_id" bson:"_id"`
	}
)

type OXYDesignPropertyData struct{}

func NewOXYDesignPropertyData() *OXYDesignPropertyData {
	data := &OXYDesignPropertyData{}
	return data
}

func (opd *OXYDesignPropertyData) GetProductPropertyListHandler(c echo.Context) error {
	log.Info("GetProductPropertyListHandler")
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_property"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().Query(M, currentpage, perpage)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []designproperty{}
	query.All(&ps)
	for index, item := range ps {
		queryList := []bson.M{}
		for _, c := range item.DesignCompose {
			if len(c.Item) == 24 {
				obj := bson.M{"_id": bson.ObjectIdHex(c.Item)}
				queryList = append(queryList, obj)
			}
		}
		if len(queryList) == 0 {
			continue
		}
		model.DB().Dbname = "OxyDic"
		model.DB().Document = "Property"
		propertyInfoQuery, _, err := model.DB().Query(bson.M{"$or": queryList}, 0, 0)
		if err != nil {
			log.Error("查询出错", err)
		}
		propertyInfo := []property.Property{}
		propertyInfoQuery.All(&propertyInfo)
		ps[index].DesignComposeInfo = propertyInfo
	}

	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  ps,
		"count": count,
	})

	return nil
}

func (opd *OXYDesignPropertyData) AddProductPropertyHandler(c echo.Context) error {
	o := &insertdesignproperty{}
	log.Info("design AddProductPropertyHandler")
	version := c.QueryParam("version")
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_property"
	err := model.DB().Insert(o)
	selector := bson.M{}

	if version == "v3" {
		model.DB().Document = "product_plan_order"
		selector = bson.M{"relpro": o.DesignPlanID}
	} else {
		model.DB().Document = "design_plan"
		selector = bson.M{"_id": bson.ObjectIdHex(o.DesignPlanID)}
	}
	log.Info(version)
	log.Info(model.DB().Document)
	log.Info(o.DesignPlanID)

	data := bson.M{"$set": bson.M{"propertystatus": o.PropertyStatus}}
	err = model.DB().Update(selector, data)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (opd *OXYDesignPropertyData) UpdateProductPropertyHandler(c echo.Context) error {
	id := c.QueryParam("id")
	version := c.QueryParam("version")

	log.Info("UpdateProductPropertyHandler", id)

	o := &insertdesignproperty{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_property"
	err := model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, o)
	selector := bson.M{}
	if version == "v3" {
		model.DB().Document = "product_plan_order"
		selector = bson.M{"relpro": o.DesignPlanID}
		data := bson.M{"$set": bson.M{"propertystatus": o.PropertyStatus}}
		err = model.DB().Update(selector, data)
	} else {
		// 更新设计组状态
		model.DB().Document = "design_plan"
		selector = bson.M{"_id": bson.ObjectIdHex(o.DesignPlanID)}
		data := bson.M{"$set": bson.M{"propertystatus": o.PropertyStatus}}
		err = model.DB().Update(selector, data)
		//更新过会组状态
		model.DB().Document = "product_plan"
		selector = bson.M{"designplanid": o.DesignPlanID}
		data = bson.M{"$set": bson.M{"designpropertystatus": o.PropertyStatus}}
		_, err = model.DB().UpdateAll(selector, data)
	}
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (opd *OXYDesignPropertyData) DelProductPropertyHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelProductPropertyHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_property"
	err := model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
